package com.css.zfzx.sjcj.modules.hddcStratigraphy1LinePre.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSONObject;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.*;
import com.css.zfzx.sjcj.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.sjcj.common.utils.UpdateUtil;
import com.css.zfzx.sjcj.modules.hddcB1GeomorLnOnFractBlt.repository.entity.HddcB1GeomorlnonfractbltEntity;
import com.css.zfzx.sjcj.modules.hddcB1GeomorLnOnFractBlt.viewobjects.HddcB1GeomorlnonfractbltVO;
import com.css.zfzx.sjcj.modules.hddcStratigraphy1LinePre.repository.HddcStratigraphy1linepreNativeRepository;
import com.css.zfzx.sjcj.modules.hddcStratigraphy1LinePre.repository.HddcStratigraphy1linepreRepository;
import com.css.zfzx.sjcj.modules.hddcStratigraphy1LinePre.repository.entity.HddcStratigraphy1linepreEntity;
import com.css.zfzx.sjcj.modules.hddcStratigraphy1LinePre.service.HddcStratigraphy1linepreService;
import com.css.zfzx.sjcj.modules.hddcStratigraphy1LinePre.viewobjects.HddcStratigraphy1linepreQueryParams;
import com.css.zfzx.sjcj.modules.hddcStratigraphy1LinePre.viewobjects.HddcStratigraphy1linepreVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * @author zyb
 * @date 2020-11-27
 */
@Service
public class HddcStratigraphy1linepreServiceImpl implements HddcStratigraphy1linepreService {

	@Autowired
    private HddcStratigraphy1linepreRepository hddcStratigraphy1linepreRepository;
    @Autowired
    private HddcStratigraphy1linepreNativeRepository hddcStratigraphy1linepreNativeRepository;

    @Override
    public JSONObject queryHddcStratigraphy1linepres(HddcStratigraphy1linepreQueryParams queryParams, int curPage, int pageSize,String sort,String order) {
        Page<HddcStratigraphy1linepreEntity> hddcStratigraphy1lineprePage = this.hddcStratigraphy1linepreNativeRepository.queryHddcStratigraphy1linepres(queryParams, curPage, pageSize, sort, order);
        List<HddcStratigraphy1linepreVO> hddcStratigraphy1linepreVOList = new ArrayList<>();
        List<HddcStratigraphy1linepreEntity> hddcStratigraphy1linepreEntityList = hddcStratigraphy1lineprePage.getContent();
        for(HddcStratigraphy1linepreEntity hddcStratigraphy1linepreEntity : hddcStratigraphy1linepreEntityList){
            HddcStratigraphy1linepreVO hddcStratigraphy1linepreVO = new HddcStratigraphy1linepreVO();
            BeanUtils.copyProperties(hddcStratigraphy1linepreEntity, hddcStratigraphy1linepreVO);
            if(PlatformObjectUtils.isNotEmpty(hddcStratigraphy1linepreEntity.getGeologyboundaryline())) {
                String dictItemCode=String.valueOf(hddcStratigraphy1linepreEntity.getGeologyboundaryline());
                hddcStratigraphy1linepreVO.setGeologyboundarylineName(findByDictCodeAndDictItemCode("StraTouchTypeCVD",dictItemCode ));
            }
            hddcStratigraphy1linepreVOList.add(hddcStratigraphy1linepreVO);
        }
        Page<HddcStratigraphy1linepreVO> HddcStratigraphy1linepreVOPage = new PageImpl(hddcStratigraphy1linepreVOList, hddcStratigraphy1lineprePage.getPageable(), hddcStratigraphy1lineprePage.getTotalElements());
        JSONObject jsonObject = PlatformPageUtils.formatPageData(HddcStratigraphy1linepreVOPage);
        return jsonObject;
    }


    @Override
    public HddcStratigraphy1linepreEntity getHddcStratigraphy1linepre(String id) {
        HddcStratigraphy1linepreEntity hddcStratigraphy1linepre = this.hddcStratigraphy1linepreRepository.findById(id).orElse(null);
         return hddcStratigraphy1linepre;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcStratigraphy1linepreEntity saveHddcStratigraphy1linepre(HddcStratigraphy1linepreEntity hddcStratigraphy1linepre) {
        String uuid = UUIDGenerator.getUUID();
        hddcStratigraphy1linepre.setUuid(uuid);
        hddcStratigraphy1linepre.setCreateUser(PlatformSessionUtils.getUserId());
        hddcStratigraphy1linepre.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        hddcStratigraphy1linepre.setIsValid("1");
        this.hddcStratigraphy1linepreRepository.save(hddcStratigraphy1linepre);
        return hddcStratigraphy1linepre;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcStratigraphy1linepreEntity updateHddcStratigraphy1linepre(HddcStratigraphy1linepreEntity hddcStratigraphy1linepre) {
        UpdateUtil.copyNullProperties(hddcStratigraphy1linepreRepository.findByUuidAndIsValid(hddcStratigraphy1linepre.getUuid(), "1"), hddcStratigraphy1linepre);
        hddcStratigraphy1linepre.setUpdateUser(PlatformSessionUtils.getUserId());
        hddcStratigraphy1linepre.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        this.hddcStratigraphy1linepreRepository.save(hddcStratigraphy1linepre);
        return hddcStratigraphy1linepre;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteHddcStratigraphy1linepres(List<String> ids) {
        List<HddcStratigraphy1linepreEntity> hddcStratigraphy1linepreList = this.hddcStratigraphy1linepreRepository.findAllById(ids);
        if(!PlatformObjectUtils.isEmpty(hddcStratigraphy1linepreList) && hddcStratigraphy1linepreList.size() > 0) {
            for(HddcStratigraphy1linepreEntity hddcStratigraphy1linepre : hddcStratigraphy1linepreList) {
                hddcStratigraphy1linepre.setIsValid("0");
                hddcStratigraphy1linepre.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcStratigraphy1linepre.setUpdateTime(new Date());
                this.hddcStratigraphy1linepreRepository.save(hddcStratigraphy1linepre);
            }
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        List<DictItemEntity> validDictItems = PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
        return validDictItems;
    }

    @Override
    public String findByDictCodeAndDictItemCode(String dictCode, String dictItemCode){
        DictItemEntity dictItem = PlatformAPI.getDictAPI().getValidDictItemByDictCodeAndDictItemCode(dictCode, dictItemCode);
        String dictItemName = "";
        if(PlatformObjectUtils.isNotEmpty(dictItem)){
            dictItemName = dictItem.getDictItemName();
        }
        return dictItemName;
    }

    @Override
    public void exportFile(HddcStratigraphy1linepreQueryParams queryParams, HttpServletResponse response) {
        List<HddcStratigraphy1linepreEntity> yhDisasterEntities = hddcStratigraphy1linepreNativeRepository.exportYhDisasters(queryParams);
        List<HddcStratigraphy1linepreVO> list=new ArrayList<>();
        for (HddcStratigraphy1linepreEntity entity:yhDisasterEntities) {
            HddcStratigraphy1linepreVO yhDisasterVO=new HddcStratigraphy1linepreVO();
            BeanUtils.copyProperties(entity,yhDisasterVO);
            list.add(yhDisasterVO);
        }
        EasyPoiExcelUtil.exportExcel(list,"1：1万底图地层线-线","1：1万底图地层线-线",HddcStratigraphy1linepreVO.class,"1：1万底图地层线-线.xls",response);
    }

    @Override
    public String exportExcel(MultipartFile file, HttpServletResponse response) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置简析的第一行
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            // 获取到Excel数据
            ExcelImportResult<HddcStratigraphy1linepreVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), HddcStratigraphy1linepreVO.class, params);
            List<HddcStratigraphy1linepreVO> list = result.getList();
            // Excel条数据
            //int firstList = list.size();
            StringBuilder sb = new StringBuilder();
            //保存
            saveDisasterList(list, sb);
            returnMsg.append("成功导入" + (result.getList().size() ));
            returnMsg.append(sb);
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                Iterator<HddcStratigraphy1linepreVO> iterator = result.getFailList().iterator();
                while (iterator.hasNext()) {
                    HddcStratigraphy1linepreVO yhDisasterVO = iterator.next();
                    String error = "";
                    returnMsg.append("第" + yhDisasterVO.getRowNum() + "行" + yhDisasterVO.getErrorMsg() + "<br/>");
                    returnMsg.append(error);
                }
            }
            return returnMsg.toString();
        } catch (Exception e) {

            return "导入失败，请检查数据正确性";
        }
    }
    /**
     * 批量存入库表并且返回错误数量
     *
     * @param list
     * @param message
     * @return
     */
    public void saveDisasterList(List<HddcStratigraphy1linepreVO> list, StringBuilder message) {
        for (int i = 0; i < list.size(); i++) {
            HddcStratigraphy1linepreEntity yhDisasterEntity = new HddcStratigraphy1linepreEntity();
            HddcStratigraphy1linepreVO yhDisasterVO = list.get(i);
            // 将VO数据映射拷贝到库表中
            BeanUtils.copyProperties(yhDisasterVO, yhDisasterEntity);
            saveHddcStratigraphy1linepre(yhDisasterEntity);
        }
    }
}
